package com.gf.exam.service.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gf.base.type.ExamType;
import com.gf.base.type.PlayMode;
import com.gf.common.bean.Page;
import com.gf.exam.dao.AnswerDao;
import com.gf.exam.dao.CellDao;
import com.gf.exam.dao.ExamDao;
import com.gf.exam.model.Cell;
import com.gf.exam.model.Exam;
import com.gf.exam.model.Timer;
import com.gf.exam.service.ExamCellService;
import com.gf.user.model.User;

@Transactional
@Service("examCellService")
public class ExamCellServiceImpl implements ExamCellService {

	@Autowired
	private ExamDao examDao;

	@Autowired
	private CellDao cellDao;

	@Autowired
	private AnswerDao answerDao;

	private static final Log logger = LogFactory
			.getLog(ExamCellServiceImpl.class);

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public long save(User user, String title, String introduction, int cellNo,
			boolean active, int repeatFrom, int repeatTo, PlayMode playMode,
			int repeatTime, int exTimerH, int exTimerM, int exTimerS,
			String examType, String[] htmlContents) {

		Timer exTimer = new Timer(exTimerH, exTimerM, exTimerS);
		long examId = examDao.insert(user.getId(), user.getNickname(), title,
				introduction, cellNo, active, repeatFrom, repeatTo, playMode,
				repeatTime, exTimer, ExamType.valueOf(examType));

		int result = cellDao.insertBatch(examId, htmlContents);

		if (result != cellNo) {
			try {
				throw new Exception("保存项目失败：result->" + result + "  cellNo->"
						+ cellNo);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 所有的PPT都保存
		return result == cellNo ? examId : 0;

	}

	/**
	 * 更新项目整体信息<br>
	 * 删除该项目下的所有PPT<br>
	 * 再重新插入
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public long update(long id, String title, String introduction, int cellNo,
			boolean active, int repeatFrom, int repeatTo, PlayMode playMode,
			int repeatTime, int exTimerH, int exTimerM, int exTimerS,
			String[] htmlContents) {

		examDao.update(id, title, introduction, cellNo, active, repeatFrom,
				repeatTo, playMode, repeatTime, new Timer(exTimerH, exTimerM,
						exTimerS), ExamType.PRIVATE);
		// 删除该项目下的所有PPT
		cellDao.delete(id);
		// 重新插入
		int result = cellDao.insertBatch(id, htmlContents);

		if (result != cellNo) {
			try {
				throw new Exception();
			} catch (Exception e) {
				logger.error("批量插入出错");
			}
		}
		return id;
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public long publish(long id) {
		examDao.update(id, ExamType.PUBLIC);

		return id;
	}

	@Override
	public Exam scan(long id, long userId) {
		return examDao.queryByIdAndUserId(id, userId);
	}

	@Override
	public Exam join(long id) {
		return examDao.queryById(id);
	}

	@Override
	public Page getParticipate(long userId, int curpage, int pageSize) {
		List<Long> examIds = answerDao.queryParticipate(userId);
		Page page = new Page();
		page.setCurpage(curpage);
		page.setPageSize(pageSize);
		page.setTotal(examIds.size());

		int start = page.getStartIndex();
		int end = page.getEndIndex();

		List<Exam> exams = examDao.queryBatchById(examIds.subList(start, end));
		page.setResults(exams);

		return page;
	}

	@Override
	public Page getMyExam(long userId, int curpage, int pageSize,
			ExamType examType) {
		Page page = new Page();
		page.setCurpage(curpage);
		page.setPageSize(pageSize);
		page.setTotal(examDao.queryTotalCount(userId, examType));
		List<Exam> exams = examDao.queryByUserId(userId, page, examType);
		page.setResults(exams);

		return page;
	}

	@Override
	@Transactional(readOnly = true)
	public Cell getCell(long examId, int number) {

		return cellDao.queryByOne(examId, number);
	}

	@Override
	public Page getAll(int pageSize, int currentPage) {
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(pageSize);
		page.setTotal(examDao.queryExamNumber());

		page.setResults(examDao.queryAll(page));
		return page;
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public boolean delete(long id) {
		return examDao.delete(id);
	}

	@Override
	public int getTotal(long userId, ExamType examType) {
		return examDao.queryTotalCount(userId, examType);
	}

	@Override
	public List<Cell> getAllCells(long examId) {
		return examDao.queryAllCells(examId);
	}

	@Override
	public int getJoinNumberByUserId(long userId) {
		List<Long> result = answerDao.queryParticipate(userId);
		if (result == null) {
			return 0;
		}
		return result.size();
	}

}
